package pro.shuangxi.config;

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import pro.shuangxi.config.mvc.ServletConfig;
import pro.shuangxi.config.mybatisplus.MybatisPlusMvcConfig;
import pro.shuangxi.config.mybatisplus.MybatisPlusRootConfig;
import pro.shuangxi.config.spring.RootConfig;

import javax.servlet.*;
import java.util.EnumSet;

public class InitConfg extends AbstractAnnotationConfigDispatcherServletInitializer{

	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[]{RootConfig.class, MybatisPlusRootConfig.class};
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[]{ServletConfig.class, MybatisPlusMvcConfig.class};
	}

	@Override
	protected FilterRegistration.Dynamic registerServletFilter(ServletContext servletContext, Filter filter) {
		return super.registerServletFilter(servletContext, filter);
	}

	@Override
	protected String[] getServletMappings() {
		return new String[]{"*.do"};
	}


	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		servletContext.addFilter("characterEncoding", new CharacterEncodingFilter()).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true, "/*");


		final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
		final CorsConfiguration corsConfiguration = new CorsConfiguration();
		//是否允许请求带有验证信息
		corsConfiguration.setAllowCredentials(true);
		// 允许访问的客户端域名
		corsConfiguration.addAllowedOrigin("*");
		// 允许服务端访问的客户端请求头
		corsConfiguration.addAllowedHeader("*");
		// 允许访问的方法名,GET POST等
		corsConfiguration.addAllowedMethod("*");
		urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
		servletContext.addFilter("corsFilter", new CorsFilter(urlBasedCorsConfigurationSource)).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true, "/*");

		System.out.println("http://localhost:8080");
		super.onStartup(servletContext);
	}
}
